package net.kts.placebook.venue;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import net.kts.location.MyLocationManager;
import net.kts.main.R;
import net.kts.placebook.dao.PlacebookDao;
import net.kts.placebook.oath.ActivityWebView;
import net.kts.placebook.session.FoursquareSession;
import net.kts.placebook.session.UMISSession;
import net.kts.placebook.tips.TipsList;
import net.kts.transrate.TranslateService;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class NearbyVenues extends ListActivity {

	public static final String tagName = "fs333";
	
	private ProgressDialog mProgress;
	private ArrayList<Venue> mNearbyList;
	private NearbyAdapter mAdapter;
	private PlacebookDao dao;
	private FoursquareSession session = null;
	
	private LocationListener locationListener = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pb_nearby_list);
		
		session = new FoursquareSession(this);
        mProgress		= new ProgressDialog(this);
        mNearbyList		= new ArrayList<Venue>();
        mAdapter 		= new NearbyAdapter(this);
        dao 			= new PlacebookDao(this);
        
        // 액세스 토큰이 없으면 웹뷰 띄워 인증하도록 함.
		if(session.getAccessToken() == null){
			Intent intent = new Intent(NearbyVenues.this, ActivityWebView.class);
			startActivity(intent);

			String accessToken = (String) net.kts.placebook.session.UMISSession.getInstance().getObjectByKey("accessToken");
			if (accessToken != null) {
				session.storeAccessToken(accessToken);
				Log.i(tagName, "토큰 저장 완료");
			} else {
				Log.i(tagName, "액세스 토큰 없음");
			}	
		}else{
	        // 내 위치 찾기
			
			if(this.locationListener == null) {
				locationListenerInit();
				MyLocationManager.addLocationListener(this.locationListener);
			}
			
			changeLocation(MyLocationManager.giveMeMyCurrentLocation());
			double lat = MyLocationManager.giveMeMyCurrentLocation().getAltitude();
			double lon = MyLocationManager.giveMeMyCurrentLocation().getLongitude();
			
			// 사용자 위치 값이 없을 경우 기본으로 논현역 지정
			if(UMISSession.getInstance().getObjectByKey("lat") == null){
				Log.i(tagName, "::사용자 위치 값 없음:: ");
				// 논현역 경도 위도 
				lat = 37.51121;
				lon = 127.021729 ;
			}else{
				lat = (Double) UMISSession.getInstance().getObjectByKey("lat");
				lon = (Double) UMISSession.getInstance().getObjectByKey("long");
				Log.i(tagName, "사용자 위치 :: " + lat + ", " + lon);
			}
			
			loadNearbyPlaces(lat, lon);
		}
	}
	
    @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 액세스 토큰이 있는지 확인.. 없으면 웹뷰 띄워 토큰 받도록 함.
				if(session.getAccessToken() == null){
					Intent intent = new Intent(NearbyVenues.this, ActivityWebView.class);
					startActivity(intent);
					
					// 토큰 저장 이벤트
					Log.i(tagName, "::토큰 저장 이벤트::");
					String accessToken = (String) net.kts.placebook.session.UMISSession.getInstance().getObjectByKey("accessToken");
					if (accessToken != null) {
						session.storeAccessToken(accessToken);
						Log.i(tagName, "토큰 저장 완료");
					} else {
						Log.i(tagName, "액세스 토큰 없음");
					}	
				}else{
			        // 내 위치 찾기
					if(this.locationListener == null) {
						locationListenerInit();
						MyLocationManager.addLocationListener(this.locationListener);
					}

					changeLocation(MyLocationManager.giveMeMyCurrentLocation());
					
					double lat = MyLocationManager.giveMeMyCurrentLocation().getAltitude();
					double lon = MyLocationManager.giveMeMyCurrentLocation().getLongitude();
					
					// 사용자 위치 값이 없을 경우 기본으로 논현역 지정
					if(UMISSession.getInstance().getObjectByKey("lat") == null){
						Log.i(tagName, "::사용자 위치 값 없음:: ");
						// 논현역 경도 위도 
						lat = 37.51121;
						lon = 127.021729 ;
					}else{
						lat = (Double) UMISSession.getInstance().getObjectByKey("lat");
						lon = (Double) UMISSession.getInstance().getObjectByKey("long");
						Log.i(tagName, "사용자 위치 :: " + lat + ", " + lon);
					}
					
					loadNearbyPlaces(lat, lon);
				}

	}



	private void loadNearbyPlaces(final double latitude, final double longitude) {
		String wait = TranslateService.translateRepository("잠시만 기다려주세요.");
		if(wait == null){
			mProgress.setMessage("Please wait a moment.");
		}else if(wait.trim().equals("")){
			mProgress.setMessage("Please wait a moment.");
		}else{
			mProgress.setMessage(wait);
		}
		
    	mProgress.show();

    	new Thread() {
    		@Override
    		public void run() {
    			int what = 0;
    			
    			try {
    				mNearbyList = dao.getNearby(latitude, longitude);
    			} catch (Exception e) {
    				Log.i(tagName, "loadNearbyPlaces Exception");
    				what = 1;
    				e.printStackTrace();
    			}
    			
    			mHandler.sendMessage(mHandler.obtainMessage(what));
    		}
    	}.start();
    }

    private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
    		mProgress.dismiss();
    		
    		Log.i(tagName, msg.toString());
    		
    		if (msg.what == 0) {
    			if (mNearbyList.size() == 0) {
    				Toast.makeText(NearbyVenues.this, "No nearby places available", Toast.LENGTH_SHORT).show();
    				return;
    			}
    			// 출력
    			mAdapter.setData(mNearbyList);    			
    			setListAdapter(mAdapter);
    		} else {
    			Toast.makeText(NearbyVenues.this, "Failed to load nearby places", Toast.LENGTH_SHORT).show();
    		}
    	}
    };

	@Override
	protected void onListItemClick(ListView list, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(list, v, position, id);
		Venue venue = (Venue) list.getItemAtPosition(position);
		
		Log.i(tagName, venue.name + ":: 정보 가져오기 호출 ::");
		
		// 액티비티 화면 전환
		Intent intent = new Intent(NearbyVenues.this, TipsList.class);
		
		intent.putExtra("venueId", venue.id);
		intent.putExtra("name", venue.name);
		intent.putExtra("address", venue.address);
		
		startActivity(intent);

	}
	
	private void locationListenerInit() {
		
		this.locationListener = new LocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				// 
//				Toast.makeText(getBaseContext(), "New location latitude ["  +
//			    		lat + "] longitude [" + lng + "]", Toast.LENGTH_SHORT).show();
				changeLocation(location);
			}
		};
		
	}
	
	public void changeLocation(Location location) {
		//this.locationFlag = true;
		// 세션에 저장
		UMISSession.getInstance().setObjectByKey("lat", location.getLatitude());
		UMISSession.getInstance().setObjectByKey("long", location.getLongitude());
		
	}
	
	private boolean isFinising = false;
    @Override
    public void onBackPressed() {
    	if(isFinising){
    		moveTaskToBack(true);
    		android.os.Process.killProcess(android.os.Process.myPid());
    	}
    	Toast.makeText(this, TranslateService.translateRepository("다시 한번 눌러 종료하세요"), 1).show();
    	Thread timeWorker = new Thread(new Runnable() {			
			@Override
			public void run() {
				isFinising = true;
				try {
					TimeUnit.SECONDS.sleep(2);
					isFinising = false;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
    	timeWorker.start();
    }
	
}
